package com.cube.share.base.service;

import com.cube.share.base.function.CatchExceptionFunction;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.RunnableFuture;

/**
 * @author poker.li
 * @date 2021/7/12 14:26
 * <p>
 * 异步调用服务类
 */
@Service
@Async
@SuppressWarnings("unused")
public class AsyncExecuteService {

    /**
     * 异步执行
     *
     * @param runnable 方法
     */
    public void execute(Runnable runnable) {
        runnable.run();
    }

    /**
     * 异步执行并获取执行结果
     *
     * @param runnableFutureTask runnableFutureTask {@link RunnableFuture }
     * @param <FR>               泛型
     * @return 执行后的方法本身, 可通过 get()获取执行结果,注意该方法是阻塞的,直至获取到执行结果或者抛出异常
     */
    public <FR extends RunnableFuture<?>> FR executeWithResult(FR runnableFutureTask) {
        runnableFutureTask.run();
        return runnableFutureTask;
    }

    public void executeAndCatchException(String title, CatchExceptionFunction runnable) {
        CatchExceptionFunction.execute(title, runnable);
    }

}
